package com.main.UIOptions;

import com.gryffonx.utils.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.dom4j.tree.DefaultElement;

import javax.swing.tree.DefaultMutableTreeNode;
import java.io.File;
import java.util.List;

/**
 * @author Erik Stell
 * @version 1.0
 */
public class NameGeneratorOptionTree {
    private static final File fileToBeParsed = new File("src/com/gryffonx/xml/navigation.xml");
    private static final SAXReader reader = new SAXReader();
    private static Document xmlDoc = null;

    /**
     * @return
     */
    public static DefaultMutableTreeNode buildNavigationTree() {

        //parse the xml file
        try {
            xmlDoc = reader.read(fileToBeParsed);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        String rootName = xmlDoc.getRootElement().getName();
        //populate the tree with the various generator options
        DefaultMutableTreeNode root = new DefaultMutableTreeNode(rootName);
        List childNodes = xmlDoc.selectSingleNode("/" + rootName + "").selectNodes("*");
        for (Object childNode : childNodes) {
            DefaultElement thisObj = (DefaultElement) childNode;
            buildChildNavBlock(thisObj.getName(), rootName, root);


        }
        return root;
    }

    private static void buildChildNavBlock(String childLabel, String rootName, DefaultMutableTreeNode root) {
        DefaultMutableTreeNode names = new DefaultMutableTreeNode(StringUtils.capitalize(childLabel));

        List howMany = xmlDoc.selectSingleNode("/" + rootName + "/" + childLabel + "").selectNodes("*");
        for (Object aHowMany : howMany) {
            DefaultElement thisObj = (DefaultElement) aHowMany;
            DefaultMutableTreeNode tableNode = new DefaultMutableTreeNode(StringUtils.capitalize(thisObj.getName()));

            if (thisObj.hasMixedContent()) {
                List childNodes = xmlDoc.selectSingleNode("/" + rootName + "/" + childLabel + "/" + thisObj.getXPathNameStep()).selectNodes("*");
                for (Object childNode : childNodes) {
                    DefaultElement childElem = (DefaultElement) childNode;
                    DefaultMutableTreeNode tableChild = new DefaultMutableTreeNode(StringUtils.capitalize(childElem.getName()));
                    tableNode.add(tableChild);
                }
            }

            names.add(tableNode);
        }
        root.add(names);
    }
}